package org.william.mongodb.modules.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.william.mongodb.modules.entity.User;
import org.william.mongodb.modules.entity.William;
import org.william.mongodb.modules.service.IUserService;

import java.util.UUID;

@RestController
@RequestMapping("/mongo")
public class MongoController {
    @Autowired
    private IUserService userService;

    @PostMapping(value = "save")
    public void save(){
        User user = new User();
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        user.setId(id);
        user.setUserName("william");
        user.setPassWord("123456");
        userService.saveUser(user);
    }

    @GetMapping(value = "find")
    public User findUserByUserName(){
        return userService.findUserByUserName("william");
    }

    @PostMapping(value = "update")
    public void updateUser(){
        User user = userService.findUserByUserName("william");
        user.setUserName("williamYe");
        user.setPassWord("654321");
        userService.updateUser(user);
    }

    @DeleteMapping(value = "delete")
    public void deleteUserById(){
        User user = userService.findUserByUserName("william");
        userService.deleteUserById(user.getId());
    }

    @PostMapping(value = "saveJson")
    public String getByJSON(@RequestBody JSONObject jsonParam) {
        // 直接将json信息打印出来
        System.out.println(jsonParam.toJSONString());

        // 将获取的json数据封装一层，然后在给返回
        JSONObject result = new JSONObject();
        result.put("msg", "ok");
        result.put("method", "json");
        result.put("data", jsonParam);
        William william = new William();
        william.setJsonParam(jsonParam);
        userService.saveJSON(william);
        return result.toJSONString();
    }

}
